package com.sl.boot.admindemo.domain.role.patient.controller;


import com.sl.boot.admindemo.commmon.enums.ResponseEnum;
import com.sl.boot.admindemo.commmon.utils.RedisUtil;
import com.sl.boot.admindemo.commmon.vo.resp.BaseResp;
import com.sl.boot.admindemo.domain.role.patient.dto.PatientDTO;
import com.sl.boot.admindemo.domain.role.patient.entity.Patient;
import com.sl.boot.admindemo.domain.role.patient.service.PatientService;
import com.sl.boot.admindemo.domain.role.patient.vo.PatientVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/patient")
public class PatientController {
    @Autowired
    private PatientService patientService;

    @Resource
    RedisUtil redisUtil;

    private final String prefix = "email:";


    @GetMapping(value = "/all")
    public BaseResp getAllPatient(@RequestParam(value = "page") Integer page, @RequestParam(value = "limit") Integer limit) {
        BaseResp baseResp = new BaseResp();
        List<PatientDTO> patients = patientService.queryAllPatient(page, limit, baseResp);
        baseResp.setData(patients);
        return baseResp;
    }

    @GetMapping(value = "/getPatient")
    public BaseResp getOnePatient(@RequestParam(value = "username") String username) {
        return new BaseResp(patientService.queryOne(username));
    }

    @PostMapping(value = "update")
    public BaseResp update(@RequestBody Patient patient, @RequestParam(value = "patientName") String patientName) {
        return new BaseResp(patientService.updateOne(patient, patientName));
    }

    /**
     * 注册新患者
     *
     * @param patientVO
     * @return
     */
    @PostMapping(value = "add")
    public BaseResp add(@RequestBody PatientVO patientVO) {
        String realCode = redisUtil.get(prefix + patientVO.getEmail()).toString();
        Assert.notNull(realCode, "Redis不存在验证码");

        if (!realCode.equals(patientVO.getCode())) {
            return new BaseResp(ResponseEnum.AUTH_CODE_ERROR);
        }
        /**
         * 本身并不存储邮箱
         */
        Patient patient = new Patient();
        BeanUtils.copyProperties(patientVO, patient);
        Integer result = patientService.addOne(patient);
        return new BaseResp(result);
    }


    @GetMapping(value = "/search")
    public BaseResp search(@RequestParam(value = "patientName") String patientName) {
        return new BaseResp(patientService.search(patientName));
    }

}